Page({
  data: {
    orderData: null,
    address: {
      userName: '张三',
      telNumber: '13800138000',
      provinceName: '广东省',
      cityName: '深圳市',
      countyName: '南山区',
      detailInfo: '科技园路1号'
    },
    remark: '',
    totalAmount: 0
  },

  onLoad: function(options) {
    if (options.orderData) {
      const orderData = JSON.parse(options.orderData);
      this.setData({
        orderData: orderData.items,
        totalAmount: orderData.totalAmount
      });
    }
  },

  // 选择收货地址
  chooseAddress: function() {
    wx.chooseAddress({
      success: (res) => {
        this.setData({
          address: res
        });
      }
    });
  },

  // 输入备注
  onRemarkInput: function(e) {
    this.setData({
      remark: e.detail.value
    });
  },

  // 提交订单
  submitOrder: async function() {
    try {
      wx.showLoading({
        title: '提交中...',
      });

      // 创建订单对象
      const order = {
        id: Date.now().toString(), // 使用时间戳作为订单ID
        items: this.data.orderData,
        address: this.data.address,
        remark: this.data.remark,
        totalAmount: this.data.totalAmount,
        status: 1, // 1: 待支付
        createTime: new Date().toLocaleString(),
        orderNo: 'LE' + Date.now().toString().slice(-8) // 生成订单号
      };

      // 获取现有订单列表
      const orders = wx.getStorageSync('orders') || [];
      
      // 将新订单添加到列表开头
      orders.unshift(order);
      
      // 保存到本地存储
      wx.setStorageSync('orders', orders);

      // 模拟创建订单成功
      await new Promise(resolve => setTimeout(resolve, 1000));

      wx.hideLoading();
      wx.showToast({
        title: '下单成功',
        icon: 'success'
      });

      // 清空购物车
      const pages = getCurrentPages();
      const orderPage = pages[pages.length - 2];
      orderPage.setData({
        cart: [],
        totalAmount: 0,
        showCartBar: false,
        showCartPopup: false
      });

      // 跳转到订单列表页
      wx.switchTab({
        url: '/pages/orders/orders'
      });
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '下单失败',
        icon: 'error'
      });
    }
  }
}); 